<template>
  <div class="page">
    <h2>消防员档案管理</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按姓名/工号搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="filterRank" placeholder="全部职级" style="width:180px">
        <el-option label="全部职级" :value="''" />
        <el-option v-for="r in ranks" :key="r" :label="r" :value="r" />
      </el-select>

      <el-select v-model="filterStatus" placeholder="在职状态" style="width:140px">
        <el-option label="全部" :value="''" />
        <el-option label="在职" value="active" />
        <el-option label="离职" value="inactive" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增档案</el-button>
        <el-button @click="() => fileInput.click()">导入CSV</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="badge" label="工号" width="110" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="rank" label="职级" width="140" />
      <el-table-column prop="years" label="服役年限" width="110" />
      <el-table-column prop="contact" label="联系方式" width="140" />
      <el-table-column prop="lastAssessment" label="最近评估" width="140" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status==='active' ? 'success' : 'info'">{{ row.status==='active' ? '在职' : '离职' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="openModal(row.id)">编辑</el-button>
          <el-button size="small" @click="toggleStatus(row.id)" style="margin-left:8px">{{ row.status==='active' ? '离职' : '恢复' }}</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.id)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchSetStatus('inactive')">批量设为离职</el-button>
      <el-button @click="batchSetStatus('active')">批量恢复在职</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <!-- dialog -->
    <el-dialog :title="editingId ? '编辑档案' : '新增档案'" v-model="showModal" width="620px">
      <el-form :model="form" label-width="110px">
        <el-form-item label="工号">
          <el-input v-model="form.badge" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="form.age" :min="18" :max="70" />
        </el-form-item>
        <el-form-item label="职级">
          <el-select v-model="form.rank" style="width:200px">
            <el-option v-for="r in ranks" :key="r" :label="r" :value="r" />
          </el-select>
        </el-form-item>
        <el-form-item label="服役年限">
          <el-input-number v-model="form.years" :min="0" :max="60" />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="form.contact" />
        </el-form-item>
        <el-form-item label="既往心理病史">
          <el-input v-model="form.history" />
        </el-form-item>
        <el-form-item label="最近评估日期">
          <el-date-picker v-model="form.lastAssessment" type="date" placeholder="选择日期" style="width:180px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" style="width:160px">
            <el-option label="在职" value="active" />
            <el-option label="离职" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

    <input ref="fileInput" type="file" accept=".csv" style="display:none" @change="handleFile" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_DATA = [
  {id:1,badge:'F001',name:'张强',age:34,rank:'中队长',years:12,contact:'13800000001',history:'无',lastAssessment:'2025-08-10',status:'active'},
  {id:2,badge:'F002',name:'李静',age:29,rank:'队员',years:6,contact:'13800000002',history:'轻度焦虑史',lastAssessment:'2025-07-05',status:'active'},
  {id:3,badge:'F003',name:'王伟',age:41,rank:'副中队长',years:18,contact:'13800000003',history:'曾诊断PTSD',lastAssessment:'2025-06-20',status:'inactive'}
];

const data = ref([]);
const q = ref('');
const filterRank = ref('');
const filterStatus = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ badge:'', name:'', age:30, rank:'', years:0, contact:'', history:'', lastAssessment:'', status:'active' });
const fileInput = ref(null);

onMounted(()=>{ load(); });

function load(){ data.value = JSON.parse(JSON.stringify(DEFAULT_DATA)); }

const ranks = computed(()=>{ const s = new Set(data.value.map(i=>i.rank).filter(Boolean)); return Array.from(s.length? s : ['中队长','副中队长','队员']); });

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.name.toLowerCase().includes(qq) || (d.badge||'').toLowerCase().includes(qq))) return false;
    if(filterRank.value && d.rank !== filterRank.value) return false;
    if(filterStatus.value && d.status !== filterStatus.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.id); });

function onSelectionChange(rows){ selectedRows.value = rows; }

function openModal(id){
  editingId.value = id || null;
  if(id){ const it = data.value.find(x=>x.id===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); }
  else{ Object.assign(form,{badge:'',name:'',age:30,rank:'',years:0,contact:'',history:'',lastAssessment:'',status:'active'}); }
  showModal.value = true;
}
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.badge || !form.name){ ElMessage.warning('工号和姓名为必填项'); return; }
  if(editingId.value){ const it = data.value.find(x=>x.id===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); }
  else{ const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push(Object.assign({id:nid}, JSON.parse(JSON.stringify(form)))); }
  showModal.value=false; ElMessage.success('保存成功'); }

function deleteOne(id){ ElMessageBox.confirm('确认删除该档案？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.id!==id); ElMessage.success('已删除'); })
  .catch(()=>{});
}
function toggleStatus(id){ const it = data.value.find(x=>x.id===id); if(!it) return; it.status = it.status==='active'?'inactive':'active'; }

function getSelectedIds(){ return selectedIds.value.slice(); }
function batchSetStatus(s){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } data.value.forEach(d=>{ if(ids.includes(d.id)) d.status = s; }); ElMessage.success('操作完成'); }
function batchDelete(){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.id)); selectedIds.value = []; selectedRows.value = []; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){
  const csv = [ ['id','badge','name','age','rank','years','contact','history','lastAssessment','status'], ...data.value.map(d=>[d.id,d.badge,d.name,d.age,d.rank,d.years,d.contact,d.history||'',d.lastAssessment||'',d.status]) ];
  const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n');
  const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'});
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a'); a.href=url; a.download='firefighter_profiles.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
}

function handleFile(e){ const f = e.target.files[0]; if(!f) return; const reader = new FileReader(); reader.onload = function(ev){ try{
  const text = ev.target.result;
  const rows = text.split(/\r?\n/).map(r=>r.trim()).filter(Boolean);
  if(rows.length<2){ ElMessage.warning('没有有效数据'); return; }
  const headers = parseCSVLine(rows[0]);
  const items = rows.slice(1).map(r=>parseCSVLine(r)).map(cols=>{ const obj={}; headers.forEach((h,i)=>obj[h.trim()]=cols[i]||''); return obj; });
  items.forEach(it=>{
    const id = it.id?parseInt(it.id):null;
    if(id){ const ex = data.value.find(x=>x.id===id); if(ex){ Object.assign(ex,{badge:it.badge||ex.badge,name:it.name||ex.name,age:parseInt(it.age)||ex.age,rank:it.rank||ex.rank,years:parseInt(it.years)||ex.years,contact:it.contact||ex.contact,history:it.history||ex.history,lastAssessment:it.lastAssessment||ex.lastAssessment,status:it.status||ex.status}); return; } }
    const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1;
    data.value.push({id:nid,badge:it.badge||('F'+nid),name:it.name||'未命名',age:parseInt(it.age)||30,rank:it.rank||'',years:parseInt(it.years)||0,contact:it.contact||'',history:it.history||'',lastAssessment:it.lastAssessment||'',status:it.status||'active'});
  });
  ElMessage.success('导入完成');
 }catch(err){ ElMessage.error('导入失败'); }}; reader.readAsText(f,'utf-8'); e.target.value=''; }

function parseCSVLine(line){ const cols=[]; let cur=''; let inQ=false; for(let i=0;i<line.length;i++){ const ch=line[i]; if(inQ){ if(ch==='"'){ if(line[i+1]==='"'){ cur+='"'; i++; }else{ inQ=false; } }else{ cur+=ch; } }else{ if(ch==='"'){ inQ=true; }else if(ch===','){ cols.push(cur); cur=''; }else{ cur+=ch; } } } cols.push(cur); return cols; }

function onClear(){ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>